from flask import current_app
from app.persistence.Login import Login
from app.persistence.User import User

def update_user(user):
    from app import db  # 延迟导入，避免循环依赖
    with current_app.app_context():
        db_user = User.query.filter_by(userid=user.userid).first()
        if db_user:
            db_user.age = user.age
            db_user.username = user.username
            db_user.phone = user.phone
            db_user.introduce = user.introduce
            db.session.commit()
            return True
        return False

def update_login(user_id, password):
    from app import db  # 延迟导入，避免循环依赖
    with current_app.app_context():
        db_login = Login.query.filter_by(userid=user_id).first()
        if db_login:
            db_login.password = password
            db.session.commit()
            return True
        return False

def get_login_by_userid(userid):
    with current_app.app_context():
        login = Login.query.filter_by(userid=userid).first()
        return login

def get_user_by_userid(userid):
    with current_app.app_context():
        user = User.query.filter_by(userid=userid).first()
        return user

# 修改 create_user 方法，接收 age, phone, introduce
def create_user(user_id, username, password, age, phone, introduce=None):
    from app import db
    with current_app.app_context():
        try:
            # 强制转换 introduce 为字符串（如果不是 None）
            if introduce is not None:
                introduce = str(introduce)

            new_user = User(
                userid=user_id,
                age=age,
                username=username,
                phone=phone,
                introduce=introduce,
                status='active'
            )
            db.session.add(new_user)
            db.session.flush()  # 强制生成 userid 并同步到数据库

            print(
                f"new user created: {new_user.userid} {new_user.username} {new_user.phone} {new_user.introduce} {new_user.age}")

            new_login = Login(userid=new_user.userid, password=password)  # 使用新生成的 userid
            print(f"login: {new_user.userid} {password}")

            db.session.add(new_login)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            print(f"Error creating user: {e}")
            return False